﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class UserListPage : Page, INavigableView<UserListViewModel>
    {
        private int _themeIndex = 1;

        public UserListViewModel ViewModel { get; }

        public UserListPage(UserListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.ExecuteAsync(null);
            ViewModel.GetTreeRoleCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private async Task Edit(UserInfo info)
        {
            UserEditPage page = App.GetService<UserEditPage>();
            if (info != null)
            {
                UserEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IUserService>.Instance.GetAsync(info.Id);
                page.ViewModel.IsEdit = true;
                page.ViewModel.IsReadOnly = false;
                await page.ViewModel.InitData(info.Id);
            }
            else
            {
                page.ViewModel.Item = new UserInfo
                {
                    Password = "12345678",
                    Gender = "男",
                    Company_ID = ViewModel.PageDto.Company_ID,
                    Dept_ID = ViewModel.PageDto.Dept_ID
                };
                page.ViewModel.IsEdit = false;
                page.ViewModel.IsReadOnly = false;
            }
            page.ShowDialog();
         
            if (page.ViewModel.Result?.Success == true)
            {
                await ViewModel.GetData();
            }
        }

        [RelayCommand]
        private async Task Delete(UserInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.PageDto.Dept_ID = null;
            ViewModel.PageDto.Role_ID = null;
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<UserInfo> list = new List<UserInfo>();
                foreach (UserInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var importPage = App.GetService<ImportExcelPage>();
            importPage.ViewModel.Items?.Clear();
            importPage.ViewModel.TemplateFile = "系统用户信息-模板.xls";
            importPage.OnDataSave -= ExcelData_OnDataSave;
            importPage.OnDataSave += ExcelData_OnDataSave;
            importPage.ShowDialog();
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            string name = dr["用户名/登录名"].ToString();
            if (string.IsNullOrEmpty(name))
            {
                return false;
            }
            if (await BLLFactory<IUserService>.Instance.IsExistAsync((UserInfo s) => s.Name == name))
            {
                string key = "用户名/登录名【{0}】已存在，记录已跳过";
                key = JsonLanguage.Default.GetString(key);
                throw new ArgumentException(string.Format(key, name));
            }
            DateTime dateTime = Convert.ToDateTime("1900-01-01");
            UserInfo info = new UserInfo
            {
                HandNo = dr["用户编码"].ToString(),
                Name = name,
                FullName = dr["用户全名"].ToString(),
                Nickname = dr["用户呢称"].ToString(),
                Gender = dr["性别"].ToString(),
                MobilePhone = dr["移动电话"].ToString(),
                Email = dr["邮件地址"].ToString()
            };
            if (dr.Table.Columns.Contains("是否过期"))
            {
                info.IsExpire = dr["是否过期"].ToString().ToInt32() > 0;
            }
            if (dr.Table.Columns.Contains("职务头衔"))
            {
                info.Title = dr["职务头衔"].ToString();
            }
            if (dr.Table.Columns.Contains("身份证号码"))
            {
                info.IdentityCard = dr["身份证号码"].ToString();
            }
            if (dr.Table.Columns.Contains("办公电话"))
            {
                info.OfficePhone = dr["办公电话"].ToString();
            }
            if (dr.Table.Columns.Contains("家庭电话"))
            {
                info.HomePhone = dr["家庭电话"].ToString();
            }
            if (dr.Table.Columns.Contains("住址"))
            {
                info.Address = dr["住址"].ToString();
            }
            if (dr.Table.Columns.Contains("办公地址"))
            {
                info.WorkAddr = dr["办公地址"].ToString();
            }
            if (dr.Table.Columns.Contains("出生日期") && DateTime.TryParse(dr["出生日期"].ToString(), out var result) && result > dateTime)
            {
                info.Birthday = result;
            }
            if (dr.Table.Columns.Contains("QQ号码"))
            {
                info.QQ = dr["QQ号码"].ToString();
            }
            if (dr.Table.Columns.Contains("个性签名"))
            {
                info.Signature = dr["个性签名"].ToString();
            }
            if (dr.Table.Columns.Contains("审核状态"))
            {
                info.AuditStatus = dr["审核状态"].ToString();
            }
            if (dr.Table.Columns.Contains("备注"))
            {
                info.Note = dr["备注"].ToString();
            }
            if (dr.Table.Columns.Contains("自定义字段"))
            {
                info.CustomField = dr["自定义字段"].ToString();
            }
            if (dr.Table.Columns.Contains("排序码"))
            {
                info.SortCode = dr["排序码"].ToString();
            }
            UserInfo userInfo = App.ViewModel.UserInfo;
            info.CompanyName = userInfo.CompanyName;
            info.Company_ID = userInfo.Company_ID;
            info.DeptName = userInfo.DeptName;
            info.Dept_ID = userInfo.Dept_ID;
            info.Creator = userInfo.FullName;
            info.Creator_ID = userInfo.Id.ToString();
            info.CreateTime = DateTime.Now;
            string rowData = GetRowData(dr, "所属机构名称");
            if (!rowData.IsNullOrEmpty())
            {
                OuInfo ouInfo = await BLLFactory<IOuService>.Instance.FindByName(rowData);
                if (ouInfo != null)
                {
                    info.CompanyName = ouInfo.Name;
                    info.Company_ID = ouInfo.Id.ToString();
                }
            }
            string rowData2 = GetRowData(dr, "默认部门名称");
            if (!rowData2.IsNullOrEmpty())
            {
                OuInfo ouInfo2 = await BLLFactory<IOuService>.Instance.FindByName(rowData2);
                if (ouInfo2 != null)
                {
                    info.DeptName = ouInfo2.Name;
                    info.Dept_ID = ouInfo2.Id.ToString();
                }
            }
            return await BLLFactory<IUserService>.Instance.InsertAsync(info);
        }

        [RelayCommand]
        private void Theme()
        {
            SkinType value = (SkinType)(_themeIndex++ % 3);
            HandyControl.Themes.Theme.SetSkin(this, value);
        }

        private async void deptTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is RoleAndDeptTreeNode roleAndDeptTreeNode)
            {
                ViewModel.DeptTreeModel.SelectNode = roleAndDeptTreeNode;
                ViewModel.PageDto.Company_ID = roleAndDeptTreeNode.CompanyId;
                ViewModel.PageDto.Dept_ID = roleAndDeptTreeNode.DeptId;
                ViewModel.PageDto.Role_ID = null;
                await ViewModel.GetData();
            }
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.DeptTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.DeptTreeModel.FilteredTreeItems = ViewModel.DeptTreeModel.TreeItems;
                return;
            }
            var list = ViewModel.DeptTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
            ViewModel.DeptTreeModel.FilteredTreeItems = list;
        }

        private async void roleTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is RoleAndDeptTreeNode roleAndDeptTreeNode)
            {
                ViewModel.RoleTreeModel.SelectNode = roleAndDeptTreeNode;
                ViewModel.PageDto.Company_ID = roleAndDeptTreeNode.CompanyId;
                ViewModel.PageDto.Dept_ID = roleAndDeptTreeNode.DeptId;
                ViewModel.PageDto.Role_ID = roleAndDeptTreeNode.RoleId;
                await ViewModel.GetData();
            }
        }

        private void SearchBarRole_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.RoleTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.RoleTreeModel.FilteredTreeItems = ViewModel.RoleTreeModel.TreeItems;
                return;
            }
            ViewModel.RoleTreeModel.FilteredTreeItems = ViewModel.RoleTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }
    }
}
